'use strict';

const Service = require('egg').Service;
const fs = require('mz/fs');
const path = require("path");
class DoFormService extends Service {
  async index() {
    var {ctx} = this;
    // console.log(ctx.request.body);
    var {username,age,likes} = ctx.request.body;
    age = Number(age);
    var filename = ctx.request.files[0].filepath;
    console.log(filename);
    var reader = fs.createReadStream(filename);
    var uploadFile = `${process.cwd()}/app/public/${path.basename(filename)}`;
    var write = fs.createWriteStream(uploadFile)
    reader.pipe(write)
    var pic = ctx.origin+"/public/"+path.basename(filename);
    console.log(pic);
    var db = this.app.mongodb;
    const collection = await db.collection("list215")
    var res = await db.collection("list215").find({username}).toArray()
    // console.log(res);
    if (res.length) {
        ctx.body = "<script>alert('已添加过该成员');location.href='/form'</script>"
    } else {
        await collection.insertOne({ username, age, likes, pic })
        await ctx.redirect("/form")
    }
  }
}

module.exports = DoFormService;
